package parser

import (
	"learn-go/16.crawler2/engine"
	"learn-go/16.crawler2/model"
	"regexp"
	"strconv"
)

// <div class="m-btn purple" data-v-8b1eac0c>23岁</div>
//const ageRe = `<div class="m-btn purple" data-v-8b1eac0c>([\d]+)岁</div>`
var ageRe = regexp.MustCompile(`<div class="m-btn purple" data-v-8b1eac0c>([\d]+)岁</div>`)
var marriageRe = regexp.MustCompile(`<div class="m-btn purple" data-v-8b1eac0c>([^<]+)</div>`)
var xingzuoRe = regexp.MustCompile(`<div class="m-btn purple" data-v-8b1eac0c>([^<]+座([^<]+))</div>`)
var heightRe = regexp.MustCompile(`<div class="m-btn purple" data-v-8b1eac0c>([\d]+)cm</div>`)
var weightRe = regexp.MustCompile(`<div class="m-btn purple" data-v-8b1eac0c>([\d]+)kg</div>`)
var workPlaceRe = regexp.MustCompile(`<div class="m-btn purple" data-v-8b1eac0c>工作地:([^<]+)</div>`)
var incomeRe = regexp.MustCompile(`<div class="m-btn purple" data-v-8b1eac0c>月收入:([^<]+)</div>`)

// "genderString":"女士"
var genderRe = regexp.MustCompile(`"genderString":"([^"]+)"`)

func ParseProfile(contents []byte, name string) engine.ParseResult {
	profile := model.Profile{}
	profile.Name = name

	age, err := strconv.Atoi(extractString(contents, ageRe))
	if err == nil {
		profile.Age = age
	}
	profile.Marriage = extractString(contents, marriageRe)
	profile.Xinzuo = extractString(contents, xingzuoRe)
	height, err := strconv.Atoi(extractString(contents, heightRe))
	if err == nil {
		profile.Height = height
	}
	weight, err := strconv.Atoi(extractString(contents, weightRe))
	if err == nil {
		profile.Weight = weight
	}
	profile.Occupation = extractString(contents, workPlaceRe)
	profile.Income = extractString(contents, incomeRe)
	profile.Gender = extractString(contents, genderRe)

	result := engine.ParseResult{
		Requests: nil,
		Items:    []interface{}{profile},
	}

	return result
}

func extractString(contents []byte, re *regexp.Regexp) string {
	match := re.FindSubmatch(contents) // 找第一个

	if len(match) >= 2 {
		return string(match[1])
	} else {
		return ""
	}
}
